package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 尚通http接口
 */
public class SmsApiST extends GateWayHttpAbstract
{

    public SmsApiST(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        String t = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String,Object> params = Maps.newHashMap();
        params.put("username", paramsMaps.get("username"));
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("username") +DigestUtils.md5Hex(paramsMaps.get("password"))));
        params.put("mobile", mt.getPhone());
        String content = "";
        try {
            content = URLEncoder.encode(mt.getSmsContent(),"UTF-8");
            t = URLEncoder.encode(t,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        params.put("content", content);
        params.put("dstime", t);

        params.put("msgid", mt.getId());
        String json =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/smsSend.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        String result = "";
        List<SMSSRMessage> resultList = Lists.newArrayList();
        long code = 0l;
        try{
            code = Long.parseLong(json);
            result = "qxs"+json;
        }catch (Exception e){
            e.printStackTrace();
            result = "qxe"+json;
        }
        SMSSRMessage message = initGatewayResultMessage(result, mt, "qx");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        if(StringUtils.equals(message.getResult(), "F10199")) {
            resultCode = String.valueOf(result);
            resultMessage = String.valueOf(result);
            if(code > 0) {
                taskid = mt.getId();
                resultCode = "0";
            }
            message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
            resultList.add(message);
        }
        return resultList;
    }

    /**
     *
     * @param text 格式：号码|状态码|短信ID|扩展码|接收时间;号码|状态码|短信ID|扩展码|
     * @param rtList
     * @return
     */
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        logger.info("{}网关推送状态报告:{}", gateWayID, text);
        try {
            text = URLDecoder.decode(text,"UTF-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(text)) {
            String[] result = text.substring(7).split(";");
            for (int i = 0; i < result.length; i++) {
                String[] data = result[i].split("\\|");
                SMSRTMessage smsRtMessage = initSmsRtMessage(data[2], data[0], data[1],
                       data[1], "DELIVRD");
                rtList.add(smsRtMessage);
            }
        }
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
    	logger.info("{}网关推送用户上行:{}", gateWayID, text);
        try {
            text = URLDecoder.decode(text,"UTF-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("1");

        String[] result = text.substring(8).split("\\|");
        SMSMOMessage sMSMOMessage = new SMSMOMessage();
        sMSMOMessage.setGateWayID(gateWayID);
        sMSMOMessage.setMsgContent(result[0]);
//                sMSMOMessage.setMsgid(object.valueOf(root.element("MsgId").getStringValue()));
        sMSMOMessage.setPhone(result[3]);
        sMSMOMessage.setSenttime(result[5]);
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
        sMSMOMessage.setUuid(UUID.randomUUID().toString());
        moList.add(sMSMOMessage);
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("username",paramsMaps.get("username"));
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("username") +DigestUtils.md5Hex(paramsMaps.get("password"))));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/balanceQuery.do" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        int code = 0;
        try{
           code = Integer.parseInt(result);
            if (code != -1 || code != -2 ) {
                return "剩余短信条数：" + code;
            }
        }catch (Exception e){
            e.printStackTrace();
            return "余额查询失败";
        }

        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
//        String params = "{\"sname\":\"dlwujie\",\"spwd\":\"dlwujie1\",\"sprdid\":\"1012818\",\"apiUrl\":\"http://cf.51welink.com\"}";
        String params = "{\"username\":\"cyx\",\"password\":\"tB1cT9uL\",\"apiUrl\":\"http://120.55.248.18\"}";
        SmsApiST api = new SmsApiST("ZY",params);
//        String balance = api.balance();
//        System.out.println("balance=" + balance);
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
        message.setId("test123456");
//        api.doSend(message);
//        System.out.println(balance);
        String a = "976317672213137408";
        long b = Long.parseLong(a);
        System.out.println(b);

        String ss = "report=18268846802%7CDELIVRD%7C0321183628001430859981%7C71720%7C2018-03-21+18%3A40%3A10";
        try {
            ss = URLDecoder.decode(ss,"UTF-8");
//            api.parseReport(ss,Lists.<SMSRTMessage>newArrayList());
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        System.out.println(ss);
    }
    
}